package com.cmcc.aregister.ui.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.DataCallback_get_services;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.DataCallback_other_order;
import com.cmcc.aregister.cs.asntask.InterfaceUtils.OnCheckServiceListener;
import com.cmcc.aregister.cs.asntask.MyAsynaTask;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.constant.XmlResolve;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.Appointment;
import com.cmcc.aregister.cs.model.Department;
import com.cmcc.aregister.cs.model.Doctor;
import com.cmcc.aregister.cs.model.GeneraOrderResultModel;
import com.cmcc.aregister.cs.model.GetServicesResultModel;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.model.MemberModel;
import com.cmcc.aregister.cs.model.PayTypeModel;
import com.cmcc.aregister.cs.model.Schedule;
import com.cmcc.aregister.cs.model.ServiceInfoModel;
import com.cmcc.aregister.cs.model.User;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.OrderAdapter;
import com.cmcc.aregister.ui.adapter.OrderAdapterMsg;
import com.cmcc.aregister.ui.dialog.ServciceInfoDialog;
import com.cmcc.sdk.CmccDataStatistics;
import com.oauth.utils.EncryptUtils;
import com.unionpay.upomp.bypay.util.UPOMP;

/**
 * 订单确认界面
 * 
 * @author Administrator
 * 
 */
public class OrderDetailActivity extends ParentActivity implements
    OnClickListener, DataCallback_other_order {
    private static final String TAG = "OrderDetailActivity";
    // ------view------
    private ListView listview;
    private Button confirm_order;
    private LinearLayout content_layout;
    private LinearLayout other_order;
    private LinearLayout local_order;
    private TextView hos_name, dep_name, doc_name, order_time_other,
        order_free;
    private TextView local_hos_name, local_dep_name, local_doc_name,
        local_order_time, local_order_free;
    private TextView tv_name, tv_relation, tv_sex, tv_birth, tv_mobile,
        tv_card, tv_social;
    private Spinner contact_time;
    private TextView local_pay_type, sp_members;
    private String[] pays, memberArr;
    private EditText local_clinic_no;
    private RelativeLayout choose_service_view;
    // private Button choice_time;

    // ------parameter------
    private int currentTitleSelect = -1;
    private int area_type;
    private String unit_id = "";
    private String clinic_no = ""; // 门诊编号
    private String pay_type = "2"; // 默认支付方式为现场支付
    private String merchantcode = ""; // 医院分账ID
    private String dep_id_other = "";
    private String doc_id_other = "";
    private String detl_id = "";
    private String[] values = new String[4];
    private String guahao_amt = "";
    private boolean isLocal = true;
    private String[] time_str;
    private int choice_time_position = 0;
    private int choice_hospital_position = 0;
    private int choice_department_position = 0;
    private int choice_schedule_position = 0;
    private int choice_scheduleInfo_position = 0;
    private int choice_position = 0;
    private Map<String, Hospital> hospitalMap = new HashMap<String, Hospital>();
    private List<Hospital> hospitalList = new ArrayList<Hospital>();
    private Map<String, Department> departmentMap = new HashMap<String, Department>();
    private List<Department> departmentList = new ArrayList<Department>();
    private List<Doctor> doctorList = new ArrayList<Doctor>();
    private List<Schedule> scheduleList = new ArrayList<Schedule>();
    private List<Schedule> scheduleInfoList = new ArrayList<Schedule>();
    private Hospital hospital;
    private Department department;
    private Schedule schedule;
    private Schedule scheduleInfo;
    private boolean canChoice = false;
    private boolean orderClick = true;
    private List<MemberModel> members;
    private String params = "";

    // ------------
    private OrderAdapter orderAdapter;
    private OrderAdapterMsg orderAdapterMsg;
    private Dialog dialog;

    RadioGroup radioGroup;
    RadioButton payTypeRadio01, payTypeRadio02;

    MyAsynaTask asnTask;

    String orderDesc = "";
    String order_free_other = "0";

    private TextView service_total_price;
    private int total_price;
    String service_codes = "";
    private final String COMMON_OTHER = "0";
    private List<PayTypeModel> payTypeList = new ArrayList<PayTypeModel>();
    private MemberModel member = null;// 选择的那个member

    private HttpAsyncTask queryBindCardTask;
    /**
     * 普通或者是专家门诊
     */
    private String reservationType = "";

    /**
     * 是否来自自动预约
     */
    private String isAutoAppointment = "";
    /**
     * 班次ID
     */
    private String scheDule_id = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // showProgressDlgP(getString(R.string.notice),
        // getString(R.string.logining_info));
        Intent intent = getIntent();
        isAutoAppointment = intent.getStringExtra("isAutoAppointment");
        init(R.layout.p_order_detail);
    }

    OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkId) {
            // TODO Auto-generated method stub
            if (checkId == payTypeRadio01.getId()) {}
            if (checkId == payTypeRadio02.getId()) {}
        }
    };

    @Override
    protected void setupData() {
        if (getIntent().getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE) != null) {
            Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
                .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
            area_type = (Integer) httpMap
                .get(Arguments.ACTIVITY_JUMP_AREA_TYPE);
            members = (ArrayList<MemberModel>) httpMap
                .get(Arguments.MEMBER_LIST);
            if (area_type == R.id.left_btn) {
                isLocal = true;
            }
            else {
                isLocal = false;
            }
            // 新添加异地下单需要的参数
            dep_id_other = (String) httpMap.get(Arguments.ACTIVITY_JUMP_DEP_ID);
            doc_id_other = (String) httpMap
                .get(Arguments.ACTIVITY_JUMP_DOCTOR_ID);
            reservationType = (String) httpMap
                .get(Arguments.ACTIVITY_JUMP_CHOICE_DOCTOR_TYPE);
            // ****************
            unit_id = (String) httpMap.get(Arguments.ACTIVITY_JUMP_UNIT_ID);
            detl_id = (String) httpMap.get(Arguments.ACTIVITY_JUMP_DETL_ID);
            if (isLocal) {
                values = (String[]) httpMap
                    .get(Arguments.ACTIVITY_JUMP_ORDER_DETAIL);
                payTypeList = (ArrayList<PayTypeModel>) httpMap
                    .get(Arguments.ACTIVITY_JUMP_PAY_TYPE_LIST);
                // 自动预约
                if (isAutoAppointment != null
                    && isAutoAppointment.equals("yes")) {
                    scheDule_id = (String) httpMap
                        .get(Arguments.ACTIVITY_JUMP_SCHEDULE_ID);
                    payTypeList = new ArrayList<PayTypeModel>();
                    PayTypeModel payTypeModel = new PayTypeModel();
                    payTypeModel.cfg_code = "2";
                    payTypeModel.cfg_value = "现场支付";
                    payTypeList.add(payTypeModel);
                }
            }
            else {
                orderDesc = httpMap.get(Arguments.ACTIVITY_JUMP_ORDER_DETAIL)
                    .toString();
            }
            guahao_amt = (String) httpMap
                .get(Arguments.ACTIVITY_JUMP_GUAHAO_AMT);
            time_str = getResources().getStringArray(R.array.choice_time);
        }
        else {
            canChoice = true;
            sendGetDoctorListTask("0", ConfigUtilHelper.getMobile(app), "", "",
                "1", "0");
        }
    }

    public void setHospitalList(List<Hospital> list) {
        clearData();
        hospital = list.get(0);
        hospitalList = list;
        dialog_handler.sendMessage(dialog_handler.obtainMessage(0, 0, 0));
    }

    public void setDepartmentList(List<Department> list) {
        clearData();
        department = list.get(0);
        departmentList = list;
        for (Department dep : list) {
            departmentMap.put(dep.dep_id, dep);
            Hospital hospital = new Hospital();
            hospital.unit_id = dep.unit_id;
            hospital.unit_name = dep.unit_name;
            hospitalMap.put(hospital.unit_id, hospital);
        }
        hospital = hospitalMap.get(department.unit_id);
        dialog_handler.sendMessage(dialog_handler.obtainMessage(0, 1, 0));
    }

    public void setDoctorList(List<Doctor> list) {
        clearData();
        for (Doctor doctor : list) {
            Department dep = new Department();
            dep.dep_id = doctor.dep_id;
            dep.dep_name = doctor.dep_name;
            dep.unit_id = doctor.unit_id;
            dep.unit_name = doctor.unit_name;
            if (!departmentMap.containsKey(dep.dep_id)) {
                departmentList.add(dep);
                departmentMap.put(dep.dep_id, department);
            }
            Hospital hospital = new Hospital();
            hospital.unit_id = doctor.unit_id;
            hospital.unit_name = doctor.unit_name;
            if (!hospitalMap.containsKey(hospital.unit_id)) {
                hospitalList.add(hospital);
                hospitalMap.put(hospital.unit_id, hospital);
            }
            scheduleList.addAll(doctor.schedule_list);
        }
        schedule = scheduleList.get(0);
        hospital = hospitalMap.get(schedule.doctor.unit_id);
        department = departmentMap.get(schedule.doctor.dep_id);
        dialog_handler.sendMessage(dialog_handler.obtainMessage(0, 2, 0));
    }

    public void clearData() {
        hospitalList.clear();
        hospitalMap.clear();
        departmentList.clear();
        departmentMap.clear();
        doctorList.clear();
        scheduleList.clear();
    }

    public void setView(int type) {
        switch (type) {
        case 0:
            values = new String[4];
            values[0] = hospital.unit_name;
            break;
        case 1:
            values = new String[4];
            values[0] = department.unit_name;
            values[1] = department.dep_name;
            break;
        case 2:
            values = new String[4];
            values[0] = schedule.doctor.unit_name;
            values[1] = schedule.doctor.dep_name;
            values[2] = schedule.doctor.doctor_name + " " + schedule.to_date
                + " " + schedule.time_type;
            guahao_amt = schedule.doctor.guahao_amt;
            unit_id = schedule.doctor.unit_id;
            break;
        case 3:
            values[3] = scheduleInfo.begin_time + " - " + scheduleInfo.end_time;
            detl_id = scheduleInfo.detl_id;
            break;
        }

        if (orderAdapter == null || !orderAdapter.clickAble) {
            orderAdapter = new OrderAdapter(context, values, guahao_amt,
                type + 1, isLocal);
            listview.setAdapter(orderAdapter);
        }
        else {
            logger.e(guahao_amt);
            orderAdapter.setData(values, guahao_amt, true);
            orderAdapter.notifyDataSetChanged();
        }

    }

    private void initMemberData() {
        if (members != null && members.size() > 0) {
            memberArr = new String[members.size()];
            for (int i = 0; i < members.size(); i++) {
                memberArr[i] = members.get(i).truename;
            }
            // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            // android.R.layout.simple_spinner_item, memberArr);
            // adapter
            // .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            // sp_members.setAdapter(adapter);
            // sp_members.setOnItemSelectedListener(new OnItemSelectedListener()
            // {
            //
            // @Override
            // public void onItemSelected(AdapterView<?> arg0, View arg1,
            // int arg2, long arg3) {
            // TextView tView = (TextView) arg1;
            // tView.setTextColor(Color.BLACK);
            //
            // }
            //
            // @Override
            // public void onNothingSelected(AdapterView<?> arg0) {
            //
            // }
            //
            // });
            member = members.get(0);
            tv_relation.setText(ConfigUtilHelper.getRelationText(context,
                member.relation, member.sex));
            tv_sex.setText(member.sex == 0 ? "男" : "女");
            tv_birth.setText(member.birth);
            tv_mobile.setText(member.phone);
            tv_card.setText(member.card);
            tv_social.setText(member.social_card);
            sp_members.setText(member.truename);
        }
    }

    @Override
    protected void setupView() {
        // ((TextView)
        // findViewById(R.id.title)).setText(R.string.confirm_order);
        // top_left = (TextView) findViewById(R.id.left_btn);
        // top_right = (TextView) findViewById(R.id.right_btn);
        listview = (ListView) findViewById(R.id.listview);
        // listviewMsg = (ListView) findViewById(R.id.listview_msg);
        other_order = (LinearLayout) findViewById(R.id.other_order);
        local_order = (LinearLayout) findViewById(R.id.local_order);
        hos_name = (TextView) findViewById(R.id.hos_name);
        dep_name = (TextView) findViewById(R.id.dep_name);
        doc_name = (TextView) findViewById(R.id.doc_name);
        order_time_other = (TextView) findViewById(R.id.order_time_other);
        order_free = (TextView) findViewById(R.id.order_free);
        contact_time = (Spinner) findViewById(R.id.contact_time);

        tv_relation = (TextView) findViewById(R.id.tv_relation);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        tv_birth = (TextView) findViewById(R.id.tv_birth);
        tv_mobile = (TextView) findViewById(R.id.tv_mobile);
        tv_card = (TextView) findViewById(R.id.tv_card);
        tv_social = (TextView) findViewById(R.id.tv_social);

        local_hos_name = (TextView) findViewById(R.id.local_hos_name);
        local_dep_name = (TextView) findViewById(R.id.local_dep_name);
        local_doc_name = (TextView) findViewById(R.id.local_doc_name);
        local_order_time = (TextView) findViewById(R.id.local_order_time);
        local_order_free = (TextView) findViewById(R.id.local_order_free);
        local_clinic_no = (EditText) findViewById(R.id.local_order_clinic_no);
        local_pay_type = (TextView) findViewById(R.id.local_order_pay_type);
        local_pay_type.setOnClickListener(this);
        sp_members = (TextView) findViewById(R.id.sp_members);
        sp_members.setOnClickListener(this);

        choose_service_view = (RelativeLayout) findViewById(R.id.choose_service_view);
        choose_service_view.setOnClickListener(onClickListener);
        service_total_price = (TextView) findViewById(R.id.service_total_price);
        // choice_time = (Button) findViewById(R.id.choice_time);
        confirm_order = (Button) findViewById(R.id.confirm_order);
        content_layout = (LinearLayout) findViewById(R.id.content_layout);

        confirm_order.setOnClickListener(onClickListener);
        listview.setOnItemClickListener(onItemClickListener);

        /*
         * if (member != null) { orderAdapterMsg = new OrderAdapterMsg(this,
         * member); listviewMsg.setVisibility(View.VISIBLE);
         * listviewMsg.setAdapter(orderAdapterMsg); } else {
         * listviewMsg.setVisibility(View.GONE); }
         */
        initMemberData();

        if (isLocal) {
            other_order.setVisibility(View.GONE);
            local_order.setVisibility(View.VISIBLE);
            /*
             * orderAdapter = new OrderAdapter(context, values, guahao_amt,
             * false, isLocal); listview.setAdapter(orderAdapter);
             */
            local_hos_name.setText(values[0]);
            local_dep_name.setText(values[1]);
            local_doc_name.setText(values[2]);
            local_order_time.setText(values[3]);
            if (!"".equals(guahao_amt)) {
                local_order_free.setText(guahao_amt + getText(R.string.yuan));
            }
            if (payTypeList != null && payTypeList.size() > 0) {
                pays = new String[payTypeList.size()];
                for (int i = 0; i < pays.length; i++) {
                    pays[i] = payTypeList.get(i).cfg_value;
                }

                // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                // android.R.layout.simple_spinner_item, pays);
                // adapter
                // .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // local_pay_type
                // .setOnItemSelectedListener(new OnItemSelectedListener() {
                //
                // @Override
                // public void onItemSelected(AdapterView<?> arg0,
                // View view, int arg2, long arg3) {
                // TextView tView = (TextView) view;
                // tView.setTextColor(Color.BLACK);
                // pay_type = payTypeList.get(arg2).cfg_code;
                // merchantcode = payTypeList.get(arg2).merchantcode;
                // }
                //
                // @Override
                // public void onNothingSelected(AdapterView<?> arg0) {
                //
                // }
                //
                // });
                // local_pay_type.setAdapter(adapter);
            }
        }
        else {
            other_order.setVisibility(View.VISIBLE);
            local_order.setVisibility(View.GONE);
            String[] str = orderDesc.split(" ");
            hos_name.setText(str[2]);
            dep_name.setText(str[3]);
            doc_name.setText(str[4]);
            String time = str[5];
            for (int i = 0; i < str.length; i++) {
                if (i > 5) {
                    time = time + str[i];
                }
            }
            time = time.trim();
            order_time_other.setText(time);
            order_free.setText(order_free_other + getString(R.string.yuan)
                + getString(R.string.free));
            ArrayAdapter<CharSequence> adapter = ArrayAdapter
                .createFromResource(this, R.array.choice_time,
                    android.R.layout.simple_spinner_item);
            adapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            contact_time.setOnItemSelectedListener(mOnItemSelectedListener);
            contact_time.setAdapter(adapter);
            Map<String, String> parameterMap = new HashMap<String, String>();
            parameterMap = initArgMap(parameterMap);
            parameterMap.put("methodVit", Arguments.GetServicesOrder);
            if (reservationType.equals("1")) {
                ((LinearLayout) findViewById(R.id.contact_time_view))
                    .setBackgroundResource(R.drawable.expandable_center);
                showProgressDialog();
                new MyAsynaTask(dataGetServicesCallback,
                    GlobalSetting.XML_GET_OTHER_SERVICES, parameterMap)
                    .execute();
            }
            else {
                choose_service_view.setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.contact_time_view))
                    .setBackgroundResource(R.drawable.expandable_last);
            }
        }
    }

    ServciceInfoDialog service_dlg;
    GetServicesResultModel mGetServicesResultModel;
    /**
     * 获取异地专家门诊服务列表回调函数
     */
    DataCallback_get_services dataGetServicesCallback = new DataCallback_get_services() {

        @Override
        public void get_services(GetServicesResultModel getServicesResultModel) {
            // TODO Auto-generated method stub
            dismissProgressDialog();
            mGetServicesResultModel = getServicesResultModel;
            if (getServicesResultModel.resultCode.equals("000")) {
                service_dlg = new ServciceInfoDialog(context,
                    getServicesResultModel.serviceInfos,
                    mOnCheckServiceListener);
                if (service_dlg != null) {
                    service_dlg.show();
                }
            }
            else {
                showSingleAlertDlg(getString(R.string.get_service_info_err))
                    .show();
            }
        }
    };

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // 自动预约 修改提交任务 和支付方式显示为现场支付
        if (isAutoAppointment != null && isAutoAppointment.equals("yes")) {
            confirm_order.setText("提交任务");
            pay_type = "2";
            local_pay_type.setEnabled(false);
        }
        String result = null;
        if (isGotoPay) {
            result = UPOMP.getPayResult();
            isGotoPay = false;
        }
        if (result != null) {
            // 解析result结果
            Log.i(TAG, "--onResume--result:" + result);
            String status = null;
            try {
                status = XmlResolve.getResultInfoApi(result);
            }
            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (status != null && status.equals("0000")) {
                showSingleAlertDlg_(getString(R.string.pay_success),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {// 支付成功后关闭窗口进入支付管理页面
                                                                                // TODO
                                                                                // Auto-generated
                                                                                // method
                                                                                // stub
                            gotoAppManager();
                        }
                    }).show();
            }
            else {
                showSingleAlertDlg_(getString(R.string.pay_failed),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {// 支付成功后关闭窗口进入支付管理页面
                                                                                // TODO
                                                                                // Auto-generated
                                                                                // method
                                                                                // stub
                            gotoAppManager();
                        }
                    }).show();
            }
        }
        else {
            Log.i(TAG, "--onResume--result == null");
        }
    }

    OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
            String[] choice_str = null;
            int size = 0;
            switch (position) {
            case 1:
                size = hospitalList.size();
                choice_str = new String[size];
                for (int i = 0; i < size; i++) {
                    choice_str[i] = hospitalList.get(i).unit_name;
                }
                choice_position = choice_hospital_position;
                break;
            case 2:
                size = departmentList.size();
                choice_str = new String[size];
                for (int i = 0; i < size; i++) {
                    choice_str[i] = departmentList.get(i).dep_name;
                }
                choice_position = choice_department_position;
                break;
            case 3:
                size = scheduleList.size();
                choice_str = new String[size];
                for (int i = 0; i < size; i++) {
                    Schedule sch = scheduleList.get(i);
                    Doctor doc = sch.doctor;
                    choice_str[i] = doc.doctor_name + " " + sch.to_date + " "
                        + sch.time_type;
                }
                choice_position = choice_schedule_position;
                break;
            case 4:
                size = scheduleInfoList.size();
                choice_str = new String[size];
                for (int i = 0; i < size; i++) {
                    Schedule sch = scheduleInfoList.get(i);
                    choice_str[i] = sch.begin_time + " - " + sch.end_time;
                }
                choice_position = choice_scheduleInfo_position;
                break;
            }
            if (choice_str != null && choice_str.length > 0) {
                showChoiceDialog(choice_str, position - 1);
            }
        }
    };

    OnItemSelectedListener mOnItemSelectedListener = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int p,
            long arg3) {
            // TODO Auto-generated method stub
            TextView tView = (TextView) arg1;
            tView.setTextColor(Color.BLACK);
            choice_time_position = p;
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

    };

    public void showChoiceDialog(String[] choice_str, final int type) {
        dialog = new AlertDialog.Builder(context).setSingleChoiceItems(
            choice_str, choice_position, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog_handler.sendMessage(dialog_handler.obtainMessage(0,
                        type, which));
                    dialog.dismiss();
                }
            }).create();
        dialog.show();
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.choose_service_view) {
                if (service_dlg != null) {
                    service_dlg.show();
                }
                else {
                    showSingleAlertDlg(getString(R.string.get_service_info_err))
                        .show();
                }
                return;
            }
            if (id == R.id.confirm_order) {
                if (confirm_order
                    .getText()
                    .toString()
                    .equals(
                        OrderDetailActivity.this.getString(R.string.pay_title))) {
                    loadPayWebsite(url);
                    return;
                }
                if (!Utils.isLogin(context)
                    || ConfigUtilHelper.getMobile(context).equals("")) {// 未登陆时进入登陆界面
                    Intent intent = new Intent(OrderDetailActivity.this,
                        UserLoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    return;
                }
                if (canChoice && scheduleInfo == null) {// 没有号源情况下提示
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.no_left_num),
                        getString(R.string.close));
                    return;
                }
                if (orderClick) {// 确认提交
                                 // 来自自动预约请求
                    if (isAutoAppointment != null
                        && isAutoAppointment.equals("yes")) {
                        sendAutoAppointmentTask();
                    }
                    else {
                        // 如果选择话费支付提交，要给予提醒
                        if (pay_type.equals("1")) {
                            huafeiAlert(getString(R.string.notice),
                                getString(R.string.huafei_msg),
                                getString(R.string.confirm),
                                getString(R.string.cancel));
                        }
                        else {
                            sendGetUserInfoTask(ConfigUtilHelper
                                .getMobile(context));
                        }
                    }
                }
                else {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.confirm_again),
                        getString(R.string.close));
                }
            }
            else {
                check(id, true);
            }
        }
    };

    // 话费支付提示
    private void huafeiAlert(String title, String msg, String posTitle,
        String nagativeTitle) {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(false)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    sendGetUserInfoTask(ConfigUtilHelper.getMobile(context));
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create().show();
    }

    private void checkIsBind() {
        params = "cid=8&token=wxcityMobileClient&mid="
            + ConfigUtilHelper.getMobile(app);
        queryBindCardTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_GET_BINDCARD, Arguments.CHECK_BIND_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        queryBindCardTask.setUIHandler(queryBindCardTaskHandler);
        mHttpManager.execute(queryBindCardTask);
    }

    private Handler queryBindCardTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> map = (Map<String, Object>) msg.obj;
                    String status = (String) map.get(Arguments.XML_STATUS);
                    if (status.equals("-1")) {
                        showAlertDlg(getString(R.string.notice), unionPayMsg
                            + "," + getString(R.string.payagain_suer_msg),
                            getString(R.string.dialog_yes),
                            getString(R.string.pay_a_moment));
                    }
                    else if (status.equals("1")) {
                        showSingleAlertDlg_(
                            getString(R.string.order_confirm_success),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {
                                    confirm_order
                                        .setText(getString(R.string.pay_title));
                                    gotoAppManager();// 直接进入预约管理
                                }
                            }).show();
                    }
                    else {
                        showMsg(R.string.read_member_fail);
                    }
                }
                else {
                    showMsg(R.string.read_member_fail);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.get_bind_info_err),
                    getString(R.string.close));
                break;
            }
        };
    };

    /**
     * 银联绑定支付
     * 
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void showAlertDlg(String title, String msg, String posTitle,
        String nagativeTitle) {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(false)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    addBankCardActivity();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gotoAppManager();
                    }
                }).create().show();
    }

    public void check(int id, boolean hasAnimation) {
        if (currentTitleSelect == id) {
            return;
        }
        if (currentTitleSelect > 0) {
            findViewById(currentTitleSelect).setSelected(false);
        }
        currentTitleSelect = id;
        findViewById(currentTitleSelect).setSelected(true);
        if (hasAnimation) {
            start3DAnimation(content_layout);
        }
    }

    /**
     * 自动预约下单
     */
    private HttpAsyncTask sendAutoAppointmentTask;

    private void sendAutoAppointmentTask() {
        logger.d("----------sendAutoAppointmentTask----------");
        JSONObject obj = new JSONObject();
        try {
            obj.put("request_type", Arguments.AddAppointTaskRemoting);
            obj.put("user_mobile", ConfigUtilHelper.getMobile(app));
            obj.put("channel", "medical_client_android");
            obj.put("version",
                ConfigUtilHelper.getVersionName(getApplication()));
            obj.put("appoint_mobile", member.phone);
            obj.put("mid", member.member_id);
            obj.put("uid", unit_id);
            obj.put("schedule_id", scheDule_id);
            obj.put("detl_id", detl_id);
            obj.put("clinic_no", "");
            obj.put("merchantcode", "");
            obj.put("pay_method", pay_type);
            obj.put("member_name", member.truename);
            obj.put("hospital_name", values[0]);
            obj.put("section_name", values[1]);
            String str[] = values[2].split(" ");
            String doctor_name = str[0];
            String appoint_date = str[1];
            obj.put("doctor_name", doctor_name);
            obj.put("appoint_date", appoint_date);
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        params = obj.toString();
        String url = Arguments.GET_AUTO_APPOINT_SERVICE_URL;
        sendAutoAppointmentTask = new HttpAsyncTask(
            GlobalSetting.XML_ADD_AUTO_APPOINT, url, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true, true);
        showProgressDialogNew(R.string.dialog_loading_generatal_task);
        sendAutoAppointmentTask.setUIHandler(sendAutoAppointmentTaskHandler);
        mHttpManager.execute(sendAutoAppointmentTask);
    }

    Handler sendAutoAppointmentTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendAutoAppointmentTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String message = (String) httpMap.get(Arguments.RESULT_MSG);
                    _showInfoDialog(message,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                int which) {

                            }
                        });
                }
                else {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.cancel_task_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    public void doSomeWork() {
        Intent intent = new Intent(OrderDetailActivity.this,
            AppointActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    };

    /**
     * 提交本地预约订单
     */
    private HttpAsyncTask sendConfirmAppointmentTask;

    /**
     * 
     * @param mobile 手机号码
     * @param member_id 成员编号
     * @param unit_id 医院ID
     * @param detl_id 号源编号
     * @param clinic_no 就诊卡号
     * @param pay_method 支付方式 1 小额支付；2 现场支付；4 手机支付
     * @param merchantcode 医院分帐ID （提交订单 如果是选择小额支付需要提交此参数）
     */
    private void sendConfirmAppointmentTask(String mobile, String member_id,
        String unit_id, String detl_id, String clinic_no, String pay_method,
        String merchantcode) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        // parameterMap.put("cid", "8");
        // parameterMap.put("token", "wxcityMobileClient");
        // parameterMap.put("phone", mobile);
        // parameterMap.put("mid", member_id);// 家庭成员ID
        // parameterMap.put("uid", unit_id);
        // parameterMap.put("detlid", detl_id);
        // parameterMap.put("clinic_no", clinic_no);
        // parameterMap.put("pay_method", pay_method);
        parameterMap.put("client_auth", "test");
        parameterMap.put("token", "123456");
        StringBuffer sb = new StringBuffer();
        sb.append("mobile=").append(mobile).append("&unit_id=").append(unit_id)
            .append("&detl_id=").append(detl_id).append("&clinic_no=")
            .append(clinic_no).append("&pay_method=").append(pay_method)
            .append("&mid=").append(member_id).append("&type=").append(2);
        String entryStr = "";
        try {
            entryStr = EncryptUtils.encode(sb.toString());
            // 处理特殊参数
            entryStr = URLEncoder.encode(entryStr, "UTF-8");
        }
        catch (Exception e) {
            Log.i(TAG, "提交本地预约订单参数加密出现错误");
        }
        parameterMap.put("s", entryStr);
        String params = Utils.getParams(parameterMap);
        sendConfirmAppointmentTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_CONFIRM_APPOINTMENT,
            Arguments.SERVER_URL_CONFIRM_APPOINTMENT, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        sendConfirmAppointmentTask
            .setUIHandler(sendConfirmAppointmentTaskHandler);
        mHttpManager.execute(sendConfirmAppointmentTask);
    }

    private String unionPayMsg = "";
    @SuppressWarnings("unchecked")
    Handler sendConfirmAppointmentTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendConfirmAppointmentTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    final String order_type = (String) httpMap
                        .get(Arguments.ACTIVITY_JUMP_TYPE);
                    int status = Integer.parseInt(httpMap.get(
                        Arguments.XML_STATUS).toString());
                    if ((Appointment) httpMap.get(Arguments.XML_APPOINTMENT) != null) {
                        orderNo = ((Appointment) httpMap
                            .get(Arguments.XML_APPOINTMENT)).yuyue_id;
                    }
                    else {
                        orderNo = (String) httpMap.get(Arguments.XML_ORDER_NO);
                    }
                    String message = (String) httpMap
                        .get(Arguments.XML_MESSAGE);
                    unionPayMsg = message;
                    if (status == 0) {
                        orderClick = false;
                        app.confirm_order_success = true;
                        // 选择银联支付时，查询当前用户是否绑定银行卡
                        if (pay_type.equals("21")) {
                            checkIsBind();
                        }
                        else {
                            showSingleAlertDlg_(message,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                        int which) {
                                        confirm_order
                                            .setText(getString(R.string.pay_title));
                                        gotoAppManager();// 直接进入预约管理
                                        // 询问是否需要进行小额支付（手机号支付）
                                        // 屏蔽在线小额支付-20121015
                                        // showAlertDlg_card(getString(R.string.pay_type_title),getString(R.string.dialog_yes),getString(R.string.pay_a_moment));
                                        // showAlertDlg(getString(R.string.notice),getString(R.string.pay_suer_msg),getString(R.string.dialog_yes),getString(R.string.pay_a_moment));
                                        // ************************10.10注释的不需要支付的方式*******************************************
                                        /*
                                         * if(payTypeRadio02.isChecked()){
                                         * showAlertDlg(getString
                                         * (R.string.notice),getString
                                         * (R.string.pay_suer_msg
                                         * ),getString(R.string.dialog_yes ),
                                         * getString(R.string.pay_a_moment) );
                                         * }else{ gotoAppManager(); }
                                         */
                                        // gotoAppManager();10.10注释的
                                        // if(order_type.equals("1")){屏蔽支付（异地会返回1，本地返回0）
                                        // gotoAppManager();
                                        // return;
                                        // }
                                        // showAlertDlg_card(getString(R.string.pay_type_title),getString(R.string.dialog_yes),getString(R.string.pay_a_moment));
                                        // ******************************************
                                    }
                                }).show();
                        }
                    }
                    else {
                        if (pay_type.equals("21")) {
                            checkIsBind();
                        }
                        else {
                            showSingleAlertDlg(getString(R.string.notice),
                                message, getString(R.string.close));
                        }
                    }

                }
                else {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.order_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.order_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 获取用户信息
     */
    private HttpAsyncTask sendGetUserInfoTask;

    private void sendGetUserInfoTask(String mobile) {
        logger.d("----------sendGetUserInfoTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        String changeUserInfoUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_USER_INFO, parameterMap);
        sendGetUserInfoTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_GET_USER_INFO, changeUserInfoUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);
        showProgressDialogNew(R.string.dialog_loading_generatal_order_cancel);
        sendGetUserInfoTask.setUIHandler(sendGetUserInfoTaskHandler);
        mHttpManager.execute(sendGetUserInfoTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetUserInfoTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetUserInfoTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    User user = (User) httpMap.get(Arguments.XML_USER);
                    if ("".equals(user.card) || "null".equals(user.card)
                        || "".equals(user.birth) || "".equals(user.birth)) {
                        dismissProgressDialog();
                        // showInfoDialog(R.string.no_register, true);
                        showMsg(R.string.no_register);
                        Intent intent = new Intent(OrderDetailActivity.this,
                            PersonInfoEditor.class);
                        intent.putExtra(Arguments.ACTIVITY_IS_USER, false);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                    else {
                        if (isLocal) {
                            CmccDataStatistics
                                .onEvent(OrderDetailActivity.this, 0,
                                    "generation_order");
                            clinic_no = local_clinic_no.getText().toString();
                            sendConfirmAppointmentTask(
                                ConfigUtilHelper.getMobile(app),
                                member.member_id, unit_id, detl_id, clinic_no,
                                pay_type, merchantcode);
                        }
                        else {
                            // makeOtherOrderTask(detl_id, orderDesc,
                            // ConfigUtilHelper.getMobile(app), user.name,
                            // user.birth, user.sex,
                            // time_str[choice_time_position], order_free_other,
                            // user.card);
                            makeOtherOrderTask(detl_id, orderDesc,
                                ConfigUtilHelper.getMobile(app),
                                member.truename, member.birth,
                                String.valueOf(member.sex),
                                time_str[choice_time_position],
                                order_free_other, member.card);
                        }
                    }
                }
                else {
                    dismissProgressDialog();
                    showMsg(R.string.no_register);
                    Intent intent = new Intent(OrderDetailActivity.this,
                        PersonInfoEditor.class);
                    intent.putExtra(Arguments.ACTIVITY_IS_USER, false);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 初始化参数
     * 
     * @param parameterMap
     * @return
     */
    private Map<String, String> initArgMap(Map<String, String> parameterMap) {
        parameterMap.put("userId", Arguments.userId);
        parameterMap.put("timestamp", ConfigUtilHelper.getStringNow());
        parameterMap.put("userPwd", ConfigUtilHelper.getUserPwd());
        return parameterMap;
    }

    /**
     * 异地就医下单（新）
     * 
     * @param page
     */
    private void makeOtherOrderTask(String recordId, String orderDesc,
        String mobile, String userName, String birth, String sex,
        String bestContactTime, String orderFee, String idCard) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap = initArgMap(parameterMap);
        parameterMap.put("methodVit", Arguments.GenerationOrder);
        parameterMap.put("recordId", recordId);
        parameterMap.put("orderDesc", orderDesc);
        parameterMap.put("mobile", mobile);
        parameterMap.put("userName", userName);
        parameterMap.put("birth", birth);
        parameterMap.put("sex", sex);
        parameterMap.put("bestContactTime", bestContactTime);
        parameterMap.put("orderFee", orderFee);
        parameterMap.put("source", "1");
        parameterMap.put("orderType", "1");
        parameterMap.put("idCard", idCard);

        parameterMap.put("serviceCode", service_codes);
        parameterMap.put("reservationType", reservationType);
        parameterMap.put("doctorId", doc_id_other);
        parameterMap.put("deptId", dep_id_other);
        parameterMap.put("hospitalId", unit_id);
        parameterMap.put("serviceSumPrice", Integer.toString(total_price));
        asnTask = new MyAsynaTask(this,
            GlobalSetting.XML_GENERATION_OTHER_ORDER, parameterMap);
        asnTask.execute();
    }

    /**
     * 异地就医下单
     */
    private HttpAsyncTask sendOtherOrderTask;

    /**
     * 
     * @param mobile
     * @param service_desc 用户需求描述
     * @param unit_id 医院ID
     * @param link_best_time 最佳联系时间 现在;30分钟后; 1小时后; 上午10点-11点; 中午12点-13点;
     *        晚上19点-20点
     */
    private void sendOtherOrderTask(String mobile, String service_desc,
        String unit_id, String link_best_time) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("mobile", mobile);
        parameterMap.put("service_desc", service_desc);
        parameterMap.put("unit_id", unit_id);
        parameterMap.put("link_best_time", link_best_time);
        String orderOtheUrl = Utils.changeUrl(Arguments.SERVER_URL_ORDER_OTHE,
            parameterMap);
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "GlobalSetting.XML_ORDER_OTHE:"
                + GlobalSetting.XML_ORDER_OTHE);
        }
        sendOtherOrderTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_ORDER_OTHE, orderOtheUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, false);

        sendOtherOrderTask.setUIHandler(sendConfirmAppointmentTaskHandler);
        mHttpManager.execute(sendOtherOrderTask);
    }

    /**
     * 获取医院列表
     */
    private HttpAsyncTask sendGetHospitalListTask;

    /**
     * 
     * @param area_type 区域类别 0：本地 1：异地 2 所有
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param is_attention 是否已关注 缺省时查询全部，1只返回已关注数据
     * @param page 页数 0 表示不分页为所有，分页从1开始
     * @param pageSize 每页记录数 默认为10
     */
    protected void sendGetHospitalListTask(String area_type, String mobile,
        String is_attention, String page) {
        logger.d("----------sendGetHospitalListTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        parameterMap.put("is_attention", is_attention);
        parameterMap.put("page", page);
        parameterMap.put("pageSize", Arguments.pageSize);
        String getHospitalListUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_HOSPITAL_LIST, parameterMap);
        sendGetHospitalListTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_HOSPITAL_LIST, getHospitalListUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendGetHospitalListTask.setUIHandler(sendGetHospitalListHandler);
        mHttpManager.execute(sendGetHospitalListTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetHospitalListHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetHospitalListHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    try {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        List<Hospital> hospital_1 = (List<Hospital>) httpMap
                            .get(Arguments.XML_HOSPITAL_LIST);
                        if (hospital_1.size() > 0) {
                            setHospitalList(hospital_1);
                        }
                        else {
                            // showInfoDialog(R.string.no_attention, true);
                            // handler.sendEmptyMessageDelayed(0, 2000);
                            showInfoDialog(R.string.no_attention,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                        int which) {
                                        finish();
                                    }
                                });
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        showInfoDialog(R.string.no_attention,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {
                                    finish();
                                }
                            });
                    }
                }
                else {
                    showInfoDialog(R.string.no_attention,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                int which) {
                                finish();
                            }
                        });
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                showInfoDialog(R.string.read_fail,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                break;
            }
        }
    };

    /**
     * 获取科室列表
     */
    private HttpAsyncTask sendGetDepartmentListTask;

    /**
     * 
     * @param area_type 区域类别 0：本地 1：异地 2 所有
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param unit_id 医院id 如果为空，获取所有的科室， 如果不为空，获取所在医院的科室
     * @param is_attention 是否已关注 缺省时查询全部，1只返回已关注数据
     * @param page 页数 0 表示不分页为所有，分页从1开始
     * @param pageSize 每页记录数 默认为10
     */
    protected void sendGetDepartmentListTask(String area_type, String mobile,
        String unit_id, String is_attention, String page) {
        logger.d("----------sendGetDepartmentListTask----------" + page);
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        parameterMap.put("unit_id", unit_id);
        parameterMap.put("is_attention", is_attention);
        parameterMap.put("page", page);
        String getDepartmentListUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_DEPARTMENT_LIST, parameterMap);
        sendGetDepartmentListTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_DEPARTMENT_LIST, getDepartmentListUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendGetDepartmentListTask
            .setUIHandler(sendGetDepartmentListTaskHandler);
        mHttpManager.execute(sendGetDepartmentListTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetDepartmentListTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetDepartmentListTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    try {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        List<Department> departmentList_1 = (List<Department>) httpMap
                            .get(Arguments.XML_DEPARTMENT_LIST);
                        if (departmentList_1.size() > 0) {
                            setDepartmentList(departmentList_1);
                        }
                        else {
                            if (hospital == null) {
                                sendGetHospitalListTask("0",
                                    ConfigUtilHelper.getMobile(app), "1", "0");
                            }
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        if (hospital == null) {
                            sendGetHospitalListTask("0",
                                ConfigUtilHelper.getMobile(app), "1", "0");
                        }
                    }
                }
                else {
                    if (hospital == null) {
                        sendGetHospitalListTask("0",
                            ConfigUtilHelper.getMobile(app), "1", "0");
                    }
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                sendGetHospitalListTask("0", ConfigUtilHelper.getMobile(app),
                    "1", "0");
                break;
            }
        }
    };

    /**
     * 获取医生列表
     */
    private HttpAsyncTask sendGetDoctorListTask;

    /**
     * 
     * @param area_type 区域类别 0：本地 1：异地 2 所有
     * @param mobile 手机号码 如果为空，则不处理关注相关数据
     * @param unit_id 医院id 如果为空，获取所有的科室， 如果不为空，获取所在医院的科室
     * @param dep_id 科室id 如果为空，获取所有的医生， 如果不为空，获取所在科室的医生
     * @param is_attention 是否已关注 缺省时查询全部，1只返回已关注数据
     * @param page 页数 0 表示不分页为所有，分页从1开始
     * @param pageSize 每页记录数 默认为10
     */
    protected void sendGetDoctorListTask(String area_type, String mobile,
        String unit_id, String dep_id, String is_attention, String page) {
        logger.d("----------sendGetDoctorListTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("mobile", mobile);
        if (!"".equals(unit_id)) {
            parameterMap.put("unit_id", unit_id);
        }
        if (!"".equals(dep_id)) {
            parameterMap.put("dep_id", dep_id);
        }
        parameterMap.put("is_attention", is_attention);
        parameterMap.put("page", page);
        String getDoctorListUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_DOCTOR_LIST, parameterMap);
        sendGetDoctorListTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_DOCTOR_LIST, getDoctorListUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendGetDoctorListTask.setUIHandler(sendGetDoctorListTaskHandler);
        mHttpManager.execute(sendGetDoctorListTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetDoctorListTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetDoctorListTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    try {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        List<Doctor> doctorList_1 = (List<Doctor>) httpMap
                            .get(Arguments.XML_DOCTOR_LIST);
                        if (doctorList_1.size() > 0) {
                            setDoctorList(doctorList_1);
                        }
                        else {
                            if (department == null) {
                                sendGetDepartmentListTask("0",
                                    ConfigUtilHelper.getMobile(app), "", "1",
                                    "0");
                            }
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                        if (department == null) {
                            sendGetDepartmentListTask("0",
                                ConfigUtilHelper.getMobile(app), "", "1", "0");
                        }
                    }
                }
                else {
                    if (department == null) {
                        sendGetDepartmentListTask("0",
                            ConfigUtilHelper.getMobile(app), "", "1", "0");
                    }
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                sendGetDepartmentListTask("0", ConfigUtilHelper.getMobile(app),
                    "", "1", "0");
                break;
            }
        }
    };

    /**
     * 查询出诊班次的号源信息
     */
    private HttpAsyncTask sendGetScheduleListTask;

    /**
     * 
     * @param unit_id 医院ID
     * @param schedule_id 班次
     */
    private void sendGetScheduleListTask(String unit_id, String schedule_id) {
        logger.d("----------sendGetScheduleListTask----------");
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("unit_id", unit_id);
        parameterMap.put("schedule_id", schedule_id);
        String getScheduleListUrl = Utils.changeUrl(
            Arguments.SERVER_URL_GET_SCHEDULE_LIST, parameterMap);
        sendGetScheduleListTask = new HttpAsyncTask(HttpAsyncTask.GET,
            GlobalSetting.XML_SCHEDULE_LIST, getScheduleListUrl,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        sendGetScheduleListTask.setUIHandler(sendGetScheduleListTaskHandler);
        mHttpManager.execute(sendGetScheduleListTask);
    }

    @SuppressWarnings("unchecked")
    Handler sendGetScheduleListTaskHandler = new Handler() {
        public void handleMessage(Message msg) {
            logger.d("----------sendGetScheduleListTaskHandler----------");
            switch (msg.what) {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                if (msg.obj != null) {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    scheduleInfoList = (List<Schedule>) httpMap
                        .get(Arguments.XML_SCHEDULE_LIST);
                    if (scheduleInfoList.size() > 0) {
                        scheduleInfo = scheduleInfoList.get(0);
                        setView(3);
                    }
                }
                else {
                    showSingleAlertDlg(getString(R.string.notice),
                        getString(R.string.read_fail),
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    Handler dialog_handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            int frushType = msg.arg1;
            int position = msg.arg2;
            switch (frushType) {
            case 0:
                hospital = hospitalList.get(position);
                sendGetDepartmentListTask("0", ConfigUtilHelper.getMobile(app),
                    hospital.unit_id, "0", "0");
                choice_hospital_position = position;
                break;
            case 1:
                department = departmentList.get(position);
                sendGetDoctorListTask("0", ConfigUtilHelper.getMobile(app),
                    department.unit_id, department.dep_id, "0", "0");
                choice_department_position = position;
                break;
            case 2:
                schedule = scheduleList.get(position);
                sendGetScheduleListTask(schedule.doctor.unit_id,
                    schedule.schedule_id);
                choice_schedule_position = position;
                break;
            case 3:
                scheduleInfo = scheduleInfoList.get(position);
                choice_scheduleInfo_position = position;
                break;
            }
            setView(frushType);
        }
    };

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            finish();
        }

    };

    /*
     * protected void onDestroy() { service_dlg = null; };
     */

    @Override
    protected void setTaskHandlerNull() {
        if (sendGetHospitalListTask != null) {
            sendGetHospitalListTask.setTaskBindingHandler(null);
        }
        if (sendGetDepartmentListTask != null) {
            sendGetDepartmentListTask.setTaskBindingHandler(null);
        }
        if (sendGetDoctorListTask != null) {
            sendGetDoctorListTask.setTaskBindingHandler(null);
        }
        if (sendGetScheduleListTask != null) {
            sendGetScheduleListTask.setTaskBindingHandler(null);
        }
        if (sendConfirmAppointmentTask != null) {
            sendConfirmAppointmentTask.setTaskBindingHandler(null);
        }
        if (sendGetUserInfoTask != null) {
            sendGetUserInfoTask.setTaskBindingHandler(null);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        service_dlg = null;
    }

    /**
     * 弹出支付方式对话框（现场支付，银联卡支付，小额支付等以后还会添加，目前小额支付不用作弹出对话框）
     * 
     * @param title
     * @param posTitle
     * @param nagativeTitle
     */
    public void showAlertDlg_card(String title, String posTitle,
        String nagativeTitle) {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.sure_pay_view, null);
        payTypeRadio01 = (RadioButton) view.findViewById(R.id.pay_type01);
        payTypeRadio02 = (RadioButton) view.findViewById(R.id.pay_type02);
        payTypeRadio02.setChecked(true);
        radioGroup = (RadioGroup) view.findViewById(R.id.radiogroup);
        radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(false)
            .setView(view)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    if (payTypeRadio02.isChecked()) {
                        // positiveDoworkCard();
                        positiveDowork();
                    }
                    else {
                        showSingleNoticeDlg(
                            getString(R.string.pay_order_locale),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                    int which) {
                                    gotoAppManager();
                                }
                            }).show();
                    }
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        gotoAppManager();
                    }

                }).create().show();
    }

    String url;

    /**
     * 进入银联卡支付界面
     * 
     */
    private void positiveDoworkCard() {
        // Intent intent = new Intent(this, SplashActivity.class);
        // intent.putExtra("url", url);
        // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // startActivity(intent);
        showProgressDlgP(getString(R.string.notice),
            getString(R.string.logining_info));
        // finish();
    }

    Intent intent = null;

    public void progressRunP() {
        String packageName = this.getPackageName(); // 得到安装包名称

        // 初始化手机POS环境
        com.unionpay.upomp.bypay.util.Utils.setPackageName(packageName);
        // MY_PKG是你项目的包名
        UPOMP.init();
        // 设置Intent指向AndroidManifest中设置的action
        // action的名字 改成（接入商名称_商户证书号_插件版本）例如 hanxin_303310048990001_2_0
        intent = new Intent(ConfigUtilHelper.payAction);
        // 将封装好的xml报文传入bundle
        Bundle mBundle = new Bundle();
        initUrl();
        if (ConfigUtilHelper.debug) {
            Log.i(TAG, "orderNo:" + orderNo);
        }
        String xml = ConfigUtilHelper.postXml(timestamp, timeout, msg_id,
            orderNo, amount, mobile, targetMobile);
        mBundle.putString("xml", xml);
        // xml（通过你的服务器获得）的格式（请阅读服务器） 示例： <?xml version="1.0" encoding="UTF-8" ?>
        /*
         * <upomp application="LanchPay.Req" version="1.0.0">
         * <merchantId>303310048990001</merchantId>
         * <merchantOrderId>20120216175424121305</merchantOrderId>
         * <merchantOrderTime>20120216175424</merchantOrderTime>
         * <sign>WQAU/lv3k1M4s6dBv0ge3CgzfXRgWhKn
         * +wlED1PYJQuC8sOJEC0tbPB54E4jFpHmkTryuogAxV5oqo1FEzHsRcWWIusfxhDW
         * /UvHsxGIPp2bNIfW5
         * kxFEPKkt/IfY9IoLOk9IvzoUOInPnwjBx9uA85wFWf2aR5h/csEQV9XHHQ=</sign>
         * </upomp>
         */
        // 如果你的activity关闭了，请设置pkg（插件返回要调起activity的action name），否则不需要写
        // mBundle.putString("pkg", "android.intent.action.MAIN");
        // 将bundle置于intent中
        intent.putExtras(mBundle);
        // 使用intent跳转至支付插件
    };

    public void doWorkP() {
        if (intent != null) {
            startActivity(intent);
            isGotoPay = true;
        }
        // finish();
    };

    private void initUrl() {
        orderNo = orderNo + ConfigUtilHelper.getStringNow();
        timestamp = ConfigUtilHelper.getStringNow();
        timeout = ConfigUtilHelper.getString10after();
        msg_id = ConfigUtilHelper.getMsgId();
        if (ConfigUtilHelper.debug) {
            guahao_amt = "0.01";
        }
        amount = guahao_amt;
        mobile = ConfigUtilHelper.getMobile(this);
        targetMobile = ConfigUtilHelper.getMobile(this);
        uid = ConfigUtilHelper.getUid(this);
        token = ConfigUtilHelper.getToken(this);
    }

    /**
     * 选择服务后回调显示总服务费用
     */
    OnCheckServiceListener mOnCheckServiceListener = new OnCheckServiceListener() {

        @Override
        public void onCheckService(List<String> serviceCodes) {
            // TODO Auto-generated method stub
            total_price = 0;
            service_codes = "";
            for (int i = 0; i < serviceCodes.size(); i++) {
                for (ServiceInfoModel info : mGetServicesResultModel.serviceInfos) {
                    if (info.serviceCode.equals(serviceCodes.get(i))) {
                        total_price += Integer.parseInt(info.servicePrice);
                    }
                }
                if (service_codes.equals("")) {
                    service_codes = serviceCodes.get(i);
                }
                else {
                    service_codes = service_codes + "," + serviceCodes.get(i);
                }
            }
            if (total_price > 0) {
                service_total_price.setText(total_price + ""
                    + getString(R.string.yuan));
            }
            else {
                service_total_price.setText("");
            }
        }
    };

    /**
     * 进入小额支付界面
     */
    private void positiveDowork() {
        initUrl();
        url = ConfigUtilHelper.payUrlPre + "?spID=" + ConfigUtilHelper.spID
            + "&spPwd=" + ConfigUtilHelper.spPwd + "&spCode="
            + ConfigUtilHelper.spCode + "&spType=" + ConfigUtilHelper.spType
            + "&merchantCode=" + ConfigUtilHelper.merchantCode + "&timestamp="
            + timestamp + "&msg_id=" + msg_id + "&orderNo=" + orderNo
            + "&amount=" + amount + "&mobile=" + mobile + "&targetMobile="
            + targetMobile + "&merchantName=" + ConfigUtilHelper.merchantName
            + "&merchandise=" + ConfigUtilHelper.merchandise + "&orderDesc="
            + ConfigUtilHelper.orderDesc + "&backUrl="
            + ConfigUtilHelper.backUrl + "&uid=" + uid + "&token=" + token
            + "&payType=" + ConfigUtilHelper.payType;
        loadPayWebsite(url);
        finish();
    }

    private void nagativeDoWork() {// 不进入支付界面
        gotoAppManager();
    }

    /**
     * 进入订单管理界面
     */
    private void gotoAppManager() {
        Intent intent = new Intent(OrderDetailActivity.this,
            AppManagerActivity.class);
        intent.putExtra("isLocal", isLocal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }

    // 加载支付界面
    private void loadPayWebsite(String url) {
        Intent intent = new Intent(this, PayWebsite.class);
        intent.putExtra("url", url);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    // 请求支付（换取报文）需要参数说明（用于银联支付）

    private String timestamp = "";// 提交时间戳yyyyMMddHHmmss
    private String timeout = "";// 支付超时时间
    private String msg_id = "";// 请求平台流水号,当前时间+4位随机数
    private String orderNo = "";// 订单号,当前时间+六位随机数
    private String amount = "";// 订单总金额
    private String mobile = "";// 手机号码
    private String targetMobile = "";// 接收号码
    private String uid = "";// 无线城市用户ID
    private String token = "";// 无线城市令牌

    private boolean isGotoPay = false;

    // private String backUrl01 =
    // "http://wap.szicity.com/cm/yiliao/wuxian/index.php?c=main&a=payreturn";
    // private String backUrl02 =
    // "http://211.139.161.120/pay/main/web/index.php?c=guahao&a=return";

    @Override
    public void make_order(GeneraOrderResultModel orderResultModel) {
        // TODO Auto-generated method stub
        dismissProgressDialog();
        if (orderResultModel.resultCode.equals("000")) {
            app.confirm_order_success = true;
            gotoAppManager();// 直接进入预约管理
        }
        else if (orderResultModel.resultCode.equals("002")) {
            if (orderResultModel.resultMsg.equals("")) {
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.order_fail), getString(R.string.close));
            }
            else {
                showSingleAlertDlg(getString(R.string.notice),
                    orderResultModel.resultMsg, getString(R.string.close));
            }
        }
        else {
            showSingleAlertDlg(getString(R.string.notice),
                getString(R.string.order_fail), getString(R.string.close));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.local_order_pay_type:
            new AlertDialog.Builder(this).setItems(pays,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int arg2) {
                        pay_type = payTypeList.get(arg2).cfg_code;
                        merchantcode = payTypeList.get(arg2).merchantcode;
                        local_pay_type.setText(payTypeList.get(arg2).cfg_value);
                    }
                }).show();
            break;
        case R.id.sp_members:
            new AlertDialog.Builder(this).setItems(memberArr,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int arg2) {
                        member = members.get(arg2);
                        tv_relation.setText(ConfigUtilHelper.getRelationText(
                            context, member.relation, member.sex));
                        tv_sex.setText(member.sex == 0 ? "男" : "女");
                        tv_birth.setText(member.birth);
                        tv_mobile.setText(member.phone);
                        tv_card.setText(member.card);
                        tv_social.setText(member.social_card);
                        sp_members.setText(member.truename);
                    }
                }).show();
            break;
        }
    }
}